home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4418 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: newshost.lanl.gov!tanmoy
  2. From: tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: realloc question
  5. Date: 03 Feb 1996 17:16:26 GMT
  6. Organization: Los Alamos National Laboratory
  7. Message-ID: <TANMOY.96Feb3101626@qcd.lanl.gov>
  8. References: <4ehi4b$qfo@news.texas.net> <DM5tEn.BFo@eskimo.com>
  9. NNTP-Posting-Host: qcd.lanl.gov
  10. Mime-Version: 1.0
  11. Content-Type: text
  12. In-reply-to: scs@eskimo.com's message of Fri, 2 Feb 1996 17:47:10 GMT
  13.  
  14. In article <DM5tEn.BFo@eskimo.com> scs@eskimo.com (Steve Summit)
  15. writes: 
  16. <snip>
  17.    > ptr=(struct sumthin**) realloc(ptr,(x+1) * sizeof(struct sumthin));
  18. <snip>
  19.        and wasting (not using) most of it.  The second line
  20.        should read
  21.  
  22.            ptr = (struct sumthin **)realloc(ptr,
  23.                (x+1) * sizeof(struct sumthin *));
  24.  
  25.        (This is easy to spot, if you remember the rule that
  26.        there should always be one more * in the cast than in the
  27.        sizeof.  On the other hand, the explicit cast isn't
  28.        really recommended any more.)
  29.  
  30. Actually, in these cases, the form that I personally like is
  31.  
  32. ptr1 = realloc(ptr2, (x+1) * sizeof *ptr2)
  33.  
  34. The sizeof *ptr2 forces the correct size irrespective of what type it
  35. is. Of course, things like malloc, calloc and realloc are not really
  36. type safe: the above for example does not check that ptr1 and ptr2 are
  37. indeed the same type. But usually I use it in the context:
  38.  
  39. if ( (ptr1 = realloc(ptr2, (x+1) * sizeof *ptr2)) ) ptr2 = ptr1;
  40.  
  41. and do not use ptr1 beyond that. This brings back the type safety. 
  42.  
  43. (and yes, I do not always distinguish the boolean concept true/false
  44. from integer or pointer concepts 0, NULL especially when the 0
  45. etc. indicate failure. I tend to put extra parentheses in some of
  46. these cases as an indication to some compilers that there is no typo.)
  47.  
  48. Cheers
  49. Tanmoy
  50. --
  51. tanmoy@qcd.lanl.gov(128.165.23.46) DECNET: BETA::"tanmoy@lanl.gov"(1.218=1242)
  52. Tanmoy Bhattacharya O:T-8(MS B285)LANL,NM87545 H:#9,3000,Trinity Drive,NM87544
  53. Others see <gopher://yaleinfo.yale.edu:7700/00/Internet-People/internet-mail>,
  54. <http://alpha.acast.nova.edu/cgi-bin/inmgq.pl>or<ftp://csd4.csd.uwm.edu/pub/
  55. internetwork-mail-guide>. -- <http://nqcd.lanl.gov/people/tanmoy/tanmoy.html>
  56. fax: 1 (505) 665 3003   voice: 1 (505) 665 4733    [ Home: 1 (505) 662 5596 ]
  57.